<?php

class EventLogic {

	function save (&$event)
	{
		$eventDao = new EventDAO();

		return $eventDao->save($event) == 1;
	}

	function load ($id)
	{
		$eventDao = new EventDAO();

		return $eventDao->get($id);
	}

	function saveSetlist ($arrayOfEventToSongMaps)
	{
		$eventToSongMapDao = new EventToSongMapDAO();

		foreach ($arrayOfEventToSongMaps as $eventToSongMap)
		{
			$eventToSongMapDao->save($eventToSongMap);
		}

	}

	function addToSetlist ($eventId, $additionalSongIds)
	{
		$eventToSongMapDao = new EventToSongMapDAO();

		$maxOrder = $eventToSongMapDao->findBySQL("select max(song_order) as song_order from event_to_song_map where event_id = $eventId ");
		if (count($maxOrder) > 0)
			$i = $maxOrder[0]->song_order + 1;
		else
			$i = 1;
		foreach ($additionalSongIds as $songId)
		{
			$e2smap = new EventToSongMap(0, $eventId, $songId, $i);

			$eventToSongMapDao->save($e2smap);

			$i += 1;
		}
	}

	function removeFromSetlist($eventId, $setlistId)
	{
		$eventToSongMapDao = new EventToSongMapDAO();

		$setlistItemsToDelete = $eventToSongMapDao->findWhere("event_id = $eventId and id = $setlistId");

		foreach ($setlistItemsToDelete as $itemToDelete)
		{
			$eventToSongMapDao->delete($itemToDelete);
		}
	}

	function loadSetlist ($eventId)
	{
		$songDao = new SongDAO();
		$eventToSongMapDao = new EventToSongMapDAO();

		$setlists = $eventToSongMapDao->findWhere("event_id = $eventId", "song_order");

		$final = array();
		foreach ($setlists as $setlist)
		{

			$song = $songDao->get($setlist->song_id);

			array_push($final, new SetlistSong($setlist, $song));
		}

		return $final;
	}

	function findAll()
	{
		$eventDao = new EventDAO();

		return $eventDao->findWhere("", "start desc");
	}

	function findUpcoming($number)
	{
		$eventDao = new EventDAO();

		$allUpcoming = $eventDao->findWhere("start > NOW() and event_status in (1, 2)", "start");

		$finalList = array();
		for ($i = 0; $i < $number && $i < count($allUpcoming); $i++)
		{
			array_push($finalList, $allUpcoming[$i]);
		}

		return $finalList;
	}

	function findByExample ($event)
	{
		$eventDao = new EventDAO();

		return $eventDao->findExample($event);
	}

	function findPastPublicEvents($number=0)
	{
		$eventDao = new EventDAO();

		$allUpcoming = $eventDao->findWhere("start < NOW() and is_public = 'T' and event_status in (2, 4)", "start desc");

		if ($number == 0) return $allUpcoming;

		$finalList = array();
		for ($i = 0; $i < $number && $i < count($allUpcoming); $i++)
		{
			array_push($finalList, $allUpcoming[$i]);
		}

		return $finalList;
	}

	function findUpcomingPublicEvents($number=0)
	{
		$eventDao = new EventDAO();

		$allUpcoming = $eventDao->findWhere("start > NOW() and is_public = 'T' and event_status in (2)", "start");

		if ($number == 0) return $allUpcoming;

		$finalList = array();
		for ($i = 0; $i < $number && $i < count($allUpcoming); $i++)
		{
			array_push($finalList, $allUpcoming[$i]);
		}

		return $finalList;
	}

}

?>
